package com.lagou.edu.springbootcache.config;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

import java.util.HashSet;
import java.util.Set;

@Configuration
public class ShareJedisClusterConfig {
    @Autowired
    ShareClusterRedisProperties redisProperties;

    /**
     * 注意：
     * 这里返回的JedisCluster是单例的，并且可以直接注入到其他类中去使用
     *
     * @return
     */
    @Bean("shareJedisCluster")
    public JedisCluster getJedisCluster() {
        Set<HostAndPort> nodes = new HashSet<>();
        for (String ipPort : redisProperties.getClusterNodes()) {
            String[] ipPortPair = ipPort.split(":");
            nodes.add(new HostAndPort(ipPortPair[0].trim(), Integer.valueOf(ipPortPair[1].trim())));
        }
        //需要密码连接的创建对象方式
        if (StringUtils.isEmpty(redisProperties.getPassword())) {
            return new JedisCluster(nodes, redisProperties.getRedisTimeout(), 1000, 1, new GenericObjectPoolConfig());
        } else {
            return new JedisCluster(nodes, redisProperties.getRedisTimeout(), 1000, 1, redisProperties.getPassword(), new GenericObjectPoolConfig());
        }
    }

}